/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 分离地图json文件
 *  */
const fs = require('fs');
const path = require('path');
const countryMap = require('./source/csvJson.json'); // 需要去除‘居委’两字

// 地图geoJson数据
const dir = path.join(__dirname, 'target/xzq (5).json');

// 乡镇code需要与后端对接好
const townMap = {
  妙高街道: 331123001000,
  云峰街道: 331123002000,
  新路湾镇: 331123102000,
  北界镇: 331123103000,
  金竹镇: 331123104000,
  大柘镇: 331123105000,
  石练镇: 331123106000,
  王村口镇: 331123107000,
  黄沙腰镇: 331123108000,
  三仁畲族乡: 331123200000,
  濂竹乡: 331123201000,
  应村乡: 331123202000,
  高坪乡: 331123203000,
  湖山乡: 331123204000,
  蔡源乡: 331123205000,
  焦滩乡: 331123206000,
  龙洋乡: 331123207000,
  柘岱口乡: 331123208000,
  西畈乡: 331123209000,
  垵口乡: 331123210000,
};

/**
 * 清空文件
 * */
const removeDir = p => {
  if (!fs.existsSync(p)) return;
  const statObj = fs.statSync(p);
  if (statObj.isDirectory()) {
    let dirs = fs.readdirSync(p);
    dirs = dirs.map(_dir => path.join(p, _dir));

    for (let i = 0; i < dirs.length; i += 1) {
      removeDir(dirs[i]);
    }
    fs.rmdirSync(p);
  } else {
    fs.unlinkSync(p);
  }
};

const spliceJson = ({ jsonFile, adcode, townMap = {}, countryMap = {} }) => {
  const pPath = `dist/${adcode}`;

  // 清空dist
  removeDir('dist/');
  // 读取json
  fs.readFile(jsonFile, { encoding: 'utf-8' }, (err, data) => {
    if (err) {
      console.log('err', err);
      return;
    }
    try {
      // json数据
      const mapJson = JSON.parse(data);
      const { features = [] } = mapJson;
      // 判断文件是否存在
      if (!fs.existsSync(pPath)) {
        fs.mkdirSync(path.join(__dirname, pPath), { recursive: true });
      }

      Object.keys(townMap).forEach(townName => {
        let num = 0;
        // 乡镇的行政代码
        const townCode = townMap[townName];

        // 最终的地图数据
        const finalData = {
          type: 'FeatureCollection',
          features: [],
        };

        // 当前乡镇下的所有村的名称
        const countryNames = countryMap[townName];

        if (!countryNames) return;

        countryNames.forEach(countryName => {
          // 在mapJson数据中寻找当前乡镇的村
          const currentIndex = features.findIndex(val => {
            const { properties = {} } = val;
            const { XZQMC: name } = properties;
            return name == countryName;
          });

          if (currentIndex >= 0) {
            num += 1;
            finalData.features.push(features[currentIndex]);
          } else {
            console.log('差异名称：', townName, countryName);
          }
        });
        console.log('num', num);
        try {
          // 写入乡镇JSON文件
          fs.writeFile(
            path.join(__dirname, `${pPath}/${townCode}_full.json`),
            JSON.stringify(finalData),
            { encoding: 'utf-8' },
            _err => {
              if (_err) {
                console.log('file_err', _err);
              }
            },
          );
        } catch (error) {
          console.log('error', error);
        }
      });
    } catch (error) {
      console.log('json解析出错', error);
    }
  });
};

spliceJson({
  jsonFile: dir,
  adcode: 331123, // 县一级行政编码
  townMap,
  countryMap,
});
